package keter.web.controller;

import keter.web.security.AccountAdapter;
import keter.web.security.AnonymousUserAdapter;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

@Controller
public class SecurityController {
	
	/**
	 * Returns UserAdapter object for the currently logged in user, or null if
	 * no User is logged in.
	 * 
	 * @return currently logged user or null
	 */
	public static AccountAdapter getCurrentAccount() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication != null) {
			Object principal = authentication.getPrincipal();
			if (principal instanceof AccountAdapter) {
				return ((AccountAdapter) principal);
			}
		}

		return new AnonymousUserAdapter();
	}

	/**
	 * Utility method to determine if the current user is logged in.
	 * 
	 * @return true if user is logged in
	 */
	public static boolean isLoggedIn() {
		return !(getCurrentAccount() instanceof AnonymousUserAdapter);
	}
}
